<?php

namespace App\Http\Controllers;

use App\Ad;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class AdController extends Controller{

    public function index(){
        $params = [
            'month' => (int)request('month'),
            'year' => (int)request('year'),
            'catid' => (int)request('catid'),
        ];
        $lists = Ad::where(function ($query) use ($params) {
                if ($params['month']) {
                    $query ->whereMonth('date',$params['month']);
                }
                if ($params['year']) {
                    $query ->whereYear('date',$params['year']);
                }
                if ($params['catid']) {
                    $query ->where('catid',$params['catid']);
                }
            })
            ->orderBy('date','asc')
            ->get();
        return $this->returnJson(0,'',$lists);
    }


    public function store(){
        $year = request('year');
        $data = Ad::whereYear('date',$year)->first();
        if($data){
            return $this->returnJson(1,'数据已生成');
        }
        DB::transaction(function () use($year){
            for($m=1; $m<13; $m++){
                $days = cal_days_in_month(CAL_GREGORIAN, $m, $year);
                for($d=1;$d<=$days; $d++){
                    Ad::create([
                        'date' => Carbon::createFromDate($year, $m, $d),
                        'ads'  => [
                            ['position'=>'头条','title'=>'', 'link'=>'', 'name'=> ''],
                            ['position'=>'二条','title'=>'', 'link'=>'', 'name'=> ''],
                            ['position'=>'三条','title'=>'', 'link'=>'', 'name'=> '']
                        ],
                    ]);
                }
            }
        });
        return $this->returnJson(0,'数据生成成功');
    }

    public function update(){
        $data = request()->all();
        if($data['id']){
            $info = Ad::find($data['id']);
            if(!$info){
                return $this->returnJson(1,'数据不存在');
            }
            if($info->update($data)){
                return $this->returnJson(0,'广告信息修改成功');
            }
            return $this->returnJson(1,'广告信息修改失败');
        }else{
            $result = Ad::create($data);
            if($result){
                return $this->returnJson(0,'广告信息添加成功');
            }
            return $this->returnJson(1,'广告信息添加失败');
        }

        auth()->guard('api')->user()->update($data);
        return $this->returnData(auth()->guard('api')->user());
    }


    public function destroy(){
        $id = request('id');
        if(Ad::destroy($id)){
            return $this->returnJson(0,'删除用户成功');
        }
        return $this->returnJson(1,'删除用户失败');
    }








}